package com.chesnutconsulting.reports;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.net.URLCodec;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AjaxRequestProxy extends HttpServlet {
	private Log log = LogFactory.getLog(AjaxRequestProxy.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String key = req.getParameter("paramKey");
		String val = req.getParameter("paramVal");
		
		URLCodec urlCodec = new URLCodec();
		String url = null;
		
		try {
			ServletContext context = this.getServletContext();
			String propertiesFileLoc = context.getRealPath("/WEB-INF/reports.properties");

			Properties props = new Properties();
			props.load(new FileInputStream(propertiesFileLoc));

			url = props.getProperty("ajaxUrl") + "?" + key + "=" + urlCodec.encode(val);
		} catch (Exception e) {
			log.error(e.getMessage());
			log.error(ExceptionUtils.getFullStackTrace(e));
		}

	    HttpClient client = new HttpClient();
	    GetMethod method = new GetMethod(url);
	    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
	    		new DefaultHttpMethodRetryHandler(3, false));
	    method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
	    
	    try {
	      int statusCode = client.executeMethod(method);

	      if (statusCode != HttpStatus.SC_OK) {
		        log.error("Method failed: " + method.getStatusLine());
	      }
	      
	      InputStream responseBody = method.getResponseBodyAsStream();

	      ByteArrayOutputStream baos = new ByteArrayOutputStream();
	      
	      int c;
	      while ((c = responseBody.read()) != -1) {
	    	  baos.write((char) c);
	      }
	      byte[] responseBodyBa = baos.toByteArray();
	      
	      String xmlStr = new String(responseBodyBa);
	      
	      log.info("XML Returned: " + xmlStr);
	      
	      PrintWriter pw = resp.getWriter();
	      
	      pw.print(xmlStr);
	      pw.flush();
	      
	    } catch (HttpException e) {
			log.error(e.getMessage());
			log.error(ExceptionUtils.getFullStackTrace(e));
	    } catch (IOException e) {
			log.error(e.getMessage());
			log.error(ExceptionUtils.getFullStackTrace(e));
	    } finally {
	      method.releaseConnection();
	    } 
	}
}
